package com.yc.demo.d0801;

import com.yc.demo.util.Utils;
import com.yc.demo.vo.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "UploadServlet", value = "/upload.s")
/**
 *     String location() default "";        临时文件夹
 *     long maxFileSize                    单个文件最大值限制
        *  long maxRequestSize()default    上传文件总大小限制
    *  int fileSizeThreshold()default 0;    保存文件到临时文件夹的阈值
 */
@MultipartConfig(maxFileSize = 1024 * 1024)
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //                                  文件上传字段名
        final Part image = request.getPart("image");
        image.getSubmittedFileName();// 获取文件名
        image.getSize();             // 大小
        image.getContentType();      // 类型

        // 随机命名文件名   a.jpg  => xxxx.jpg
        String fileName = image.getSubmittedFileName();
        // 提取后缀
        String suffix = fileName.replaceAll(".+(\\.\\w+)","$1");
        // 生成前缀
        String prefix = UUID.randomUUID().toString();
        fileName = prefix + suffix;
        image.write("D:\\_文件柜\\134\\0801\\" + fileName);
        String webPath = "upload/" + fileName;
        // 上传的文件统一在 upload/ 目录下
        // 127.0.0.1/xxxxx/upload/a.jpg
        Result result = new Result(1, "文件上传成功!", webPath);
        Utils.result(response, result);
    }
}
